<?php

namespace app\common\model;

use think\Exception;

class ShopPromotionAuctionModel extends BaseModel
{
    protected $name = 'shop_promotion_auction'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    protected $type = ['begin_time' => 'timestamp', 'end_time' => 'timestamp'];//类型管理

    public function goods()
    {
        return $this->belongsTo('ShopGoodsModel', 'goods_id');
    }

    public function log()
    {
        return $this->hasMany('ShopPromotionAuctionLogModel', 'goods_id');
    }

    /**
     * 读取缩略图
     * @param $value
     * @param $data
     * @return string
     */
    protected function getGoodsThumbAttr($value, $data)
    {
        if (empty($data['album'])) {
            return '';
        } else {
            $album = explode('|', $data['album']);
            return $album[0];
        }
    }

    /**
     * 获取商品信息
     * @param $value
     * @param $data
     * @return array
     */
    protected function getGoodsInfoAttr($value, $data)
    {
        $model = new ShopGoodsModel();
        return $model->getInfo($data['goods_id']);
    }

    protected function getGoodsExtendAttr($value, $data)
    {
        $model = new ShopGoodsExtendModel();
        return $model->where('goods_id', $data['goods_id'])->select();
    }

    public function getPromotionStatusTextAttr($value, $data)
    {
        $state = [
            0 => '<span class="label label-warning">未开始</span>',
            1 => '<span class="label label-success">正常</span>',
            -1 => '<span class="label label-danger">已结束</span>',
        ];
        return $state[$data['promotion_status']];
    }

    /**
     * 获取当前最高价格
     * @return mixed
     *
     */
    protected function getNowPriceAttr($skuId)
    {
        $price = $this->log()->where(['sku_id'=>$skuId,'pay_type'=>1,'status'=>1])->order('money desc')->find();
        if (empty($price)) {
            $price['money'] = $this->getData('start_money');
            $price['msg']   = '暂未有人出价';
        } else {
            $userModel    = new UserModel();
            $username     = $userModel->where('uid', $price['member_uid'])->value('username');
            $price['msg'] = '会员' . $username . '于' . date('Y/m/d H:i:s', $price['action_time']) . '出价' . $price['money'];
        }
        return $price;
    }
}